/**
 * Created by zhangsong on 2019-05-08.
 */

import React, { Component } from 'react';
import { Button, Form, Input, Radio, Select, Tooltip, Icon, Spin } from 'antd';
import { connect } from 'dva';
import { formatMessage, FormattedMessage, getLocale } from '@/utils/i18n';
import ContractorReducer from '@/dva/application/contractor';
import UserReducer from '@/dva/user';
import Style from './search.module.scss';

const { Namespace, Effects } = ContractorReducer;

@connect(
  state => ({
    contractorStore: state[Namespace],
    userStore: state[UserReducer.Namespace],
  }),
  dispatch => ({
    handleSearchSubmit: data =>
      dispatch({
        type: `${Namespace}/${Effects.listByParam}`,
        data,
      }),
    getMainContractor() {
      dispatch({
        type: `${Namespace}/${Effects.getMainContractor}`,
      });
    },
  }),
)
@Form.create()
class SearchApp extends Component {

  componentDidMount() {
    const { getMainContractor } = this.props;
    getMainContractor();
  }

  handleClear = () => {
    const { form } = this.props;
    form.setFieldsValue({
      surname: undefined,
      sex: undefined,
      otherName: undefined,
      identityCard: undefined,
      birthday: undefined,
      status: undefined,
      is_expire: undefined,
      pass_no: undefined,
      checkedSpecified: undefined,
      contract_number: undefined,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        const { handleSearchSubmit, contractorStore } = this.props;
        const { checkedSpecified = [], ...other } = values;
        const query = {
          ...other,
        };
        if (Array.isArray(checkedSpecified) && checkedSpecified.length > 0) {
          query.checkedSpecified = checkedSpecified.join('|');
        }
        handleSearchSubmit({
          query,
          page: 1,
          pageSize: contractorStore.pageSize,
        });
      }
    });
  };

  onDownload = () => {
    this.props.onDownload();
  };

  render() {
    const { form, userStore = {}, contractorStore, exloading } = this.props;
    const { getFieldDecorator } = form;
    const { area } = userStore;
    const { mainContractorList } = contractorStore;

    const zoneTips = Array.isArray(area) ? (
      <div className={Style.zoneTipsWrapper}>
        {area.map(item => (
          <div
            key={item.id + (getLocale() === 'en-US' ? item.areaDescEn : item.areaDescZh)}
            className={Style.zoneTipsRow}
          >
            <div className={Style.zoneTipsLabel}>{item.areaCode}</div>
            <div>=</div>
            <div>{getLocale() === 'en-US' ? item.areaDescEn : item.areaDescZh}</div>
          </div>
        ))}
      </div>
    ) : null;
    return (
      <div className={Style.searchFormWrapper}>
        <div style={{ display: 'flex', justifyContent: 'end', padding: '0 0 10px' }}>
          <Button loading={exloading} htmlType="button" icon="download" onClick={() => this.onDownload()}>
            {formatMessage('button.newdownload')}
          </Button>
        </div>
        <Form layout="inline" onSubmit={this.handleSubmit}>
          <div className="item-wrapper">
            <Form.Item label={formatMessage('applicationContractor.columns.surname.name')}>
              {getFieldDecorator('surname', {})(<Input maxLength={50} />)}
            </Form.Item>
          </div>
          <div className="item-wrapper">
            <Form.Item label={formatMessage('applicationContractor.columns.sex.name')}>
              {getFieldDecorator('sex', {})(
                <Radio.Group>
                  <Radio value={undefined}>{formatMessage('baseInfo.all')}</Radio>
                  <Radio value={0}>{formatMessage('baseInfo.male')}</Radio>
                  <Radio value={1}>{formatMessage('baseInfo.female')}</Radio>
                </Radio.Group>,
              )}
            </Form.Item>
          </div>
          <div className="item-wrapper">
            <Form.Item label={formatMessage('applicationContractor.columns.otherName.name')}>
              {getFieldDecorator('otherName', {})(<Input maxLength={50} />)}
            </Form.Item>
          </div>
          <div className="item-wrapper">
            <Form.Item label={formatMessage('applicationContractor.columns.identityCard.name')}>
              {getFieldDecorator('identityCard', {})(<Input maxLength={50} />)}
            </Form.Item>
          </div>
          {/* <div className="item-wrapper">
            <Form.Item
              label={
                <span>
                  {formatMessage('applicationContractor.columns.checkedSpecified.name')}
                  &nbsp;
                  <Tooltip title={zoneTips}>
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </span>
              }
            >
              {area == null ? (
                <Spin spinning />
              ) : (
                getFieldDecorator('checkedSpecified', {})(
                  <Select
                    showSearch
                    allowClear
                    mode="multiple"
                    style={{ width: '100%' }}
                    optionFilterProp="children"
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    loading={area === null}
                    placeholder={formatMessage('baseInfo.placeholderChecked')}
                  >
                    {Array.isArray(area)
                      ? area.map(item => (
                        <Select.Option key={item.id} value={item.areaCode}>
                          {item.areaCode}
                        </Select.Option>
                      ))
                      : null}
                  </Select>,
                )
              )}
            </Form.Item>
          </div> */}
          <div className="item-wrapper">
            <Form.Item label={formatMessage('applicationContractor.columns.contractNumber.name')}>
              {getFieldDecorator('contract_number', {})(
                <Select allowClear placeholder={formatMessage('baseInfo.placeholderChecked')}>
                  {Array.isArray(mainContractorList)
                    ? mainContractorList.map(item => (
                      <Select.Option key={item.label} value={item.label}>
                        {item.label}
                      </Select.Option>
                    ))
                    : null}
                </Select>,
              )}
            </Form.Item>
          </div>
          <div className="item-wrapper">
            <Form.Item label={formatMessage('baseInfo.approvalStatusName')}>
              {getFieldDecorator('status', {})(
                <Select allowClear placeholder={formatMessage('baseInfo.placeholderChecked')}>
                  <Select.Option value={0}>
                    <FormattedMessage id="baseInfo.needApprovalStatus" />
                  </Select.Option>
                  <Select.Option value={1}>
                    <FormattedMessage id="applicationStaff.columns.checkedApproved.approved" />
                  </Select.Option>
                  <Select.Option value={-1}>
                    <FormattedMessage id="applicationStaff.columns.checkedApproved.disapproved" />
                  </Select.Option>
                  <Select.Option value={3}>
                    <FormattedMessage id="applicationContractor.temporary.cancelled" />
                  </Select.Option>
                  {/* <Select.Option value={2}>
                    <FormattedMessage id="baseInfo.needApprovalStatus" />
                  </Select.Option> */}
                </Select>,
              )}
            </Form.Item>
          </div>
          <div className="item-wrapper">
            <Form.Item label={formatMessage('applicationCommon.readerCard.canceltakes')}>
              {getFieldDecorator('is_expire', {
                initialValue: 0,
              })(
                <Select allowClear placeholder={formatMessage('baseInfo.placeholderChecked')}>
                  <Select.Option value={0}>
                    <FormattedMessage id="baseInfo.all" />
                  </Select.Option>
                  <Select.Option value={1}>
                    <FormattedMessage id="applicationCommon.readerCard.noexpired" />
                  </Select.Option>
                  <Select.Option value={2}>
                    <FormattedMessage id="applicationCommon.readerCard.expired" />
                  </Select.Option>
                </Select>,
              )}
            </Form.Item>
          </div>
          <div className="item-wrapper">
            <Form.Item
              label={formatMessage('applicationCommon.readerCard.passno')}
            >
              {getFieldDecorator('pass_no', {})(<Input />)}
            </Form.Item>
          </div>
          <div className="item-wrapper search-button">
            <Button htmlType="button" onClick={this.handleClear}>
              {formatMessage('button.clear')}
            </Button>
            <Button type="primary" htmlType="submit">
              {formatMessage('button.search')}
            </Button>
          </div>
        </Form>
      </div>
    );
  }
}

export default SearchApp;
